import java.io.*;

// deal with missing or incomplete XML TAGS
public class Preprocess {
	public static void main(String[] args){
		String url = new String("D://Eclipse35/Java_MyFile/XMLTest/newFile.txt");
		//String newUrl = new String("newFileTag.xml");
		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					new FileInputStream(url)));
			BufferedWriter writer = new BufferedWriter(new FileWriter("newFileWithGoodTag.xml"));
			
			String line = new String();
			String[] sentences = null;
			int count = 1;
			while(( line = reader.readLine()) != null){
				line.trim();
				
				if(line.isEmpty()){
					writer.write('\n');
					continue;
				}
				
				if(line.contains("Restaurant") || line.contains("Review")){
					count++;
					writer.write(line+'\n');
					continue;
				}
				sentences = line.split("<");
				
				if(sentences.length == 3){
					System.out.println("Line no. " + count + ": Tag complete!");
					writer.write(line+'\n');
				}
				
				else if(sentences.length == 2){
					System.out.println("Line no. " + count + ": Incomplete Tag!");
					if(line.contains("value") == false){
						String tag = line.substring(line.indexOf("<")+1, line.indexOf(">"));
						String endTag = "</" + tag + ">";
						writer.write(line+" "+endTag+'\n');
					}
					else{
						String tag = line.substring(line.indexOf("<")+1, line.indexOf(" "));
						String endTag = "</" + tag + ">";
						writer.write(line+" "+endTag+'\n');
					}
					
				}
				
				else if(sentences.length == 1){
					System.out.println("Line no. " + count + ": No Tag!");
					String newLine = new String("<Other> " + line + "</Other>");
					writer.write(newLine+'\n');
				}
				count++;
				
			}
			writer.flush();
			reader.close();
			writer.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		
	}
}
